<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { getProxyData, saveProxyData, uploadFuJian } from "@/api/proxyEdit";
import { useRouter } from "vue-router";
import Refresh from "@iconify-icons/ep/refresh-left";
import SaveRs from "@iconify-icons/ep/success-filled";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { message } from "@/utils/message";
import getURL from "@/utils/http/address";
import { useURLStoreHook } from "@/store/modules/proxy";
//【1】表头（指标字段+数据表字段）
const HeadArr = ref([]);
//const rowArrAt = ref([]);
const mytable = ref();
const bodyArr = ref([]);
//const columArr = ref([]);
const proxyMiaoShu = ref();
//const router = useRoute();
const myRouter = useRouter();
const rsID = ref();
const tableName = ref();
const uploadInput = ref();
const cureeUpload = ref();
const divHeight = ref();
const useURL = useURLStoreHook();
const ids = ref([]);
//const jinyong = "20-6,21-6#20-5";
let jinyong = "";
//【3】指标对应的数据
const dataArr = ref([]);
const openDialo = obj => {
  //fType.value = data;
  cureeUpload.value = obj.target.parentElement;
  uploadInput.value.click();
  //var objNode = obj.parentElement;

  //console.log("objNode", );
};

const addEventUpload = () => {
  const table = mytable.value;
  const upObjeList = table.querySelectorAll(".fu_upload");
  upObjeList.forEach(element => {
    element.addEventListener("click", openDialo);
  });
};

const setData = values => {
  const table = mytable.value;
  let colIndex = 0;
  let ccIndex = 0;
  values.value.forEach(element => {
    element.data.forEach(() => {
      colIndex = Number(ccIndex) + Number(element.start);
      const finCell = ".s_" + element.cellid + "_" + colIndex;
      const finObj = table.querySelector(finCell);
      let innerHtml = "";
      if (element.data[ccIndex].type == "file") {
        if (useURL.isEdit) {
          innerHtml =
            "<a style='color:#409eff;font-size:12px;' class='fu_upload'>上传附件</a> <input type='text' value='" +
            element.data[ccIndex].value +
            "' style='display:none' class='t_data' data-arr='" +
            element.id +
            "-" +
            element.cellid +
            "-" +
            ccIndex +
            "-" +
            element.data[ccIndex].type +
            "'/><br style='margin-top:5px;'/>";
        }
        if (element.data[ccIndex].value != "") {
          innerHtml +=
            "<a style='color:#F00;font-size:12px;' class='fu_value' target='_blank' href='" +
            getURL +
            "\\wwwroot\\proxyFiles\\" +
            element.data[ccIndex].value +
            "'>查看附件</a>";
        } else {
          innerHtml +=
            "<a style='color:#F00;display:none;font-size:12px;' target='_blank' class='fu_value' href=''>查看附件</a>";
        }
      } else if (element.data[ccIndex].type == "select") {
        if (useURL.isEdit) {
          innerHtml =
            "<select style='border:1px solid #ccc;padding:5px;width:100%;color:#409eff' class='t_data' data-arr='" +
            element.id +
            "-" +
            element.cellid +
            "-" +
            ccIndex +
            "-" +
            element.data[ccIndex].type +
            "'><option>" +
            element.data[ccIndex].value +
            "</option>";
          element.data[ccIndex].arr.split("#").forEach(el => {
            innerHtml += "<option>" + el + "</option>";
          });
          innerHtml += "</select>";
        } else {
          innerHtml =
            "<font style='color:#1b74d0;'>" +
            element.data[ccIndex].value +
            "</font>";
        }
      } else {
        if (useURL.isEdit) {
          innerHtml =
            "<input type='text' value='" +
            element.data[ccIndex].value +
            "' style='border:1px solid #ccc;padding:5px;width:120px;color:#409eff' class='t_data' data-arr='" +
            element.id +
            "-" +
            element.cellid +
            "-" +
            ccIndex +
            "-" +
            element.data[ccIndex].type +
            "'/>";
        } else {
          innerHtml =
            "<font style='color:#1b74d0;'>" +
            element.data[ccIndex].value +
            "</font>";
        }
      }
      finObj.innerHTML = innerHtml;
      ccIndex++;
      colIndex++;
    });
    colIndex = 0;
    ccIndex = 0;
  });
};

//[4]单元格合并的数据
const cellArr = ref([]);

//合并表格
const mergeTableRows = (row, strtCol, endCol) => {
  const table = mytable.value;
  let pre = undefined;
  let tempStr = "";
  let s = row;
  //var flag = false;
  let nextStr = "";
  for (let c = strtCol; c < endCol; c++) {
    tempStr = table.rows[row].cells[c].innerText; //获取当前列的第一个单元格数据
    s = 1;
    for (let r = row; r < table.rows.length - 1; r++) {
      pre = table.rows[r].cells[c].previousSibling.rowSpan;
      if (pre > 1) {
        for (let num = r; num < r + pre - 1; num++) {
          nextStr = table.rows[num + 1].cells[c].innerText;

          if (tempStr == nextStr) {
            table.rows[s].cells[c].rowSpan += 1;
            table.rows[num + 1].cells[c].className = "del";
          } else {
            s = num + 1;
            tempStr = nextStr;
          }
        }
        r += pre - 2;
      } else {
        if (tempStr == table.rows[r + 1].cells[c].innerText) {
          table.rows[s].cells[c].rowSpan += 1;
          table.rows[r + 1].cells[c].className = "del";
        } else {
          s = r + 1;
          tempStr = table.rows[r + 1].cells[c].innerText;
        }
      }
    }
  }
  const cellAll = table.querySelectorAll(".del");
  cellAll.forEach(cell => {
    cell.remove();
  });

  table.style.display = "block";
};

//返回到上一级页面
const gotoBack = () => {
  myRouter.go(-1);
};

onMounted(async () => {
  rsID.value = useURL.id;
  tableName.value = useURL.tableName;
  const Reslut = await getProxyData({
    id: rsID.value,
    tableName: tableName.value
  });
  if (Reslut.isSuccess) {
    HeadArr.value = JSON.parse(Reslut.proxHeader);
    bodyArr.value = JSON.parse(Reslut.proxBody);
    //得到所有的编码
    ids.value = bodyArr.value.map(item => item.id);
    console.log("要禁用的" + ids.value);
    cellArr.value = Reslut.proxCellArr;
    dataArr.value = Reslut.dataArr;
    jinyong = Reslut.dahCode;
    proxyMiaoShu.value = JSON.parse(Reslut.proxyMiaoShu);
  } else {
    message(Reslut.msg, { type: "error" });
  }
  nextTick(() => {
    mergeTableRows(Reslut.rowIndex, Reslut.startCol, Reslut.endCol);
    setData(dataArr);
    addEventUpload();
    //设置禁用或隐藏表格
    getJingYongCell(jinyong);
  });
  windowResize();
  window.addEventListener("resize", windowResize);
  //生态设置表格的高度
});
//获取要禁用的和隐藏的单元格
function getJingYongCell(jinyongrules: string) {
  const [jinyong, yincang] = jinyongrules.split("#");
  const table = mytable.value;
  //禁用单元格
  const pairs = jinyong.split(","); // 首先按逗号分割得到每对数字的字符串
  const numMap: Map<number, number> = new Map(); // 使用Map来存储数字对
  pairs.forEach(pair => {
    const [keyStr, valueStr] = pair.split("-"); // 再按短横线分割每对数字
    const key = parseInt(keyStr, 10);
    const value = parseInt(valueStr, 10);
    numMap.set(key, value); // 将分割出的数字存入Map
  });
  // numMap.forEach((value, key) => {
  //   table.querySelectorAll(`.s_${key}_${value}`).forEach(function (td) {
  //     td.disabled = true; // 自定义的disabled属性
  //     td.style.pointerEvents = "none";
  //     td.style.opacity = "0.5";
  //   });
  // });

  numMap.forEach((value, key) => {
    if (key != 0) {
      table.querySelectorAll(`.s_${key}_${value}`).forEach(function (td) {
        td.disabled = true; // 自定义的disabled属性
        td.style.pointerEvents = "none";
        td.style.opacity = "0.5";
      });
    } else {
      ids.value.forEach(item => {
        table.querySelectorAll(`.s_${item}_${value}`).forEach(function (td) {
          td.disabled = true; // 自定义的disabled属性
          td.style.pointerEvents = "none";
          td.style.opacity = "0.5";
        });
      });
    }
  });

  // 隐藏单元格
  const pairss = yincang.split(","); // 首先按逗号分割得到每对数字的字符串
  const numMaps: Map<number, number> = new Map();
  pairss.forEach(pair => {
    const [keyStr, valueStr] = pair.split("-");
    const key = parseInt(keyStr, 10);
    const value = parseInt(valueStr, 10);
    numMaps.set(key, value);
  });

  numMaps.forEach((value, key) => {
    if (key != 0) {
      table.querySelectorAll(`.s_${key}_${value}`).forEach(function (td) {
        td.innerText = "";
      });
    } else {
      ids.value.forEach(item => {
        table.querySelectorAll(`.s_${item}_${value}`).forEach(function (td) {
          td.innerText = "";
        });
      });
    }
  });
}

//获取数据
const save_button = async () => {
  if (useURL.isEdit) {
    const table = mytable.value;
    const allData = table.querySelectorAll(".t_data");
    console.log("修改获取的数据" + JSON.stringify(allData));
    let saveJson = "[";
    let tempStr = "";
    allData.forEach(element => {
      const sArr = element.getAttribute("data-arr").split("-");

      if (tempStr == "") {
        tempStr = sArr[0];
        saveJson +=
          '{"id":' +
          sArr[0] +
          ',"proxyid":' +
          sArr[1] +
          ',"data":[{"colIndex":"' +
          sArr[2] +
          '","dataType":"' +
          sArr[3] +
          '","dataValue":"' +
          element.value +
          '"}';
      } else {
        if (tempStr == sArr[0]) {
          saveJson +=
            ',{"colIndex":"' +
            sArr[2] +
            '","dataType":"' +
            sArr[3] +
            '","dataValue":"' +
            element.value +
            '"}';
        } else {
          tempStr = sArr[0];
          saveJson += "]},";
          saveJson +=
            '{"id":' +
            sArr[0] +
            ',"proxyid":' +
            sArr[1] +
            ',"data":[{"colIndex":"' +
            sArr[2] +
            '","dataType":"' +
            sArr[3] +
            '","dataValue":"' +
            element.value +
            '"}';
        }
      }
    });
    saveJson += "]}]";

    //console.log(saveJson);

    const postJson =
      '{"id":' +
      rsID.value +
      ',"tableName":"' +
      tableName.value +
      '","proxyDataList":' +
      saveJson +
      "}";
    const Result = await saveProxyData(JSON.parse(postJson));
    if (Result.isSuccess) {
      message("保存成功", { type: "success" });
    } else {
      message("保存失败", { type: "error" });
    }
  }
};

const handleFileChange = event => {
  const file = event.target.files[0];

  if (file && file instanceof File) {
    const reader = new FileReader();
    reader.onloadend = async () => {
      const newForm = new FormData();
      newForm.append("file", file);
      //fTypeg是上传时带的参数
      //const Result = await uploadPic(newForm, fType.value);
      const Result = await uploadFuJian(newForm);
      if (Result.isSuccess) {
        message("上传成功！", { type: "success" });

        const elObj = cureeUpload.value.querySelector(".fu_value");
        const txtObj = cureeUpload.value.querySelector(".t_data");
        elObj.setAttribute(
          "href",
          getURL + "\\wwwroot\\proxyFiles\\" + Result.msg
        );
        txtObj.setAttribute("value", Result.msg);
        elObj.style.display = "block";
      } else {
        message(Result.msg, { type: "error" });
      }
    };
    reader.readAsDataURL(file);
  }
};
//动态设置层的高度
const windowResize = () => {
  divHeight.value = window.innerHeight - 190;
};
</script>
<template>
  <div class="main">
    <div class="dataHead">
      <div class="title_left">
        <span v-for="(item, key) in proxyMiaoShu" :key="key">
          <view class="keyStyle">{{ key }} : </view>
          <view class="keyValue">{{ item }}</view>
        </span>
      </div>
      <div class="title_right">
        <el-button :icon="useRenderIcon(Refresh)" @click="gotoBack()">
          返回
        </el-button>
        <el-button
          v-if="useURL.isEdit"
          type="primary"
          :icon="useRenderIcon(SaveRs)"
          @click="save_button"
          >保存</el-button
        >
      </div>
    </div>
    <div class="dataBody" :style="{ height: divHeight + 'px' }">
      <table ref="mytable" style="width: 100%">
        <thead>
          <tr>
            <th v-for="item in HeadArr" :key="item.id">{{ item.head }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="value in bodyArr" :key="value.id">
            <td
              v-for="(citem, skey, index) in value"
              :key="index"
              :class="'s_' + value.id + '_' + index"
            >
              {{ citem }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <input
      ref="uploadInput"
      type="file"
      style="display: none"
      @change="handleFileChange"
    />
  </div>
</template>

<style scoped>
table {
  display: "block";
  width: 100%;
  border-collapse: collapse; /* 合并边框 */
}

td,
th {
  min-width: 50px;
  padding: 10px;
  font-size: 12px;
  text-align: left;
  border: 1px solid #e6e6e6; /* 设置边框大小、颜色等属性 */
}

.dataHead {
  display: block;
  width: 100%;
  height: 50px;
  padding: 10px;
  background-color: #fff;
}

.dataBody {
  width: 100%;
  margin-top: 10px;
  overflow: auto; /* 生成滚动条 */
  background-color: #ffff;
}

.dataBody table thead th {
  position: sticky;
  top: 0; /* 固定在顶部 */
  z-index: 10; /* 确保标题在最上层 */
  margin: 0;
  background-color: #e6e6e6; /* 设置背景色以避免内容下沉 */
  border-top: 0;
}

.title_left {
  float: left;
  margin-top: 10px;
  font-size: 14px;
}

.title_left span {
  margin-right: 20px;
}

.title_right {
  float: right;
}

.keyStyle {
  font-weight: bold;
  color: dimgrey;
}

.keyValue {
  color: dimgrey;
}

.myInput {
  padding: 5px;
  font-size: 16px;
  border: 1px solid #ccc;
}
</style>
